package com.zlx.sharelive.activity;

import android.app.Dialog;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.AddVideoBean;
import com.zlx.module_base.base_api.res_data.UploadBean;
import com.zlx.module_base.base_api.res_data.VideoChannelBody;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_base.base_util.TimeUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.utils.Glide4Engine;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.StringUt;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.bzcoder.mediapicker.SmartMediaPicker;
import me.bzcoder.mediapicker.config.MediaPickerEnum;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 发布短视频
 */
public class ShortVideoAc extends BaseAc {

    @BindView(R.id.iv_up_video)
    ImageView iv_up_video;
    @BindView(R.id.et_text)
    EditText et_text;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.et_title)
    EditText et_title;
    @BindView(R.id.iv_delete)
    ImageView iv_delete;
    @BindView(R.id.iv_broadcast)
    ImageView iv_broadcast;

    private List<File> fileList = new ArrayList<>();
    private String title, context, video, type;
    private String path;
    private String lat, lng, city;
    private String vip;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_short_video;
    }


    @Override
    public void initViews() {
        super.initViews();

        type = "2";

        vip = (String) SPUtil.get(this, Constants.SP_VIP, "");
    }

    @OnClick({R.id.ll_address, R.id.bt_login, R.id.iv_back
            , R.id.fl_play, R.id.iv_delete})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_delete:
                path = "";
                iv_up_video.setImageResource(R.mipmap.up_video_img);
                iv_broadcast.setVisibility(View.GONE);
                iv_delete.setVisibility(View.GONE);
                break;
            case R.id.fl_play:
                //播放
                if (!StringUt.isEmpty(path)) {
                    startActivity(new Intent(ShortVideoAc.this, ShortPreviewAc.class)
                            .putExtra("path", path));
                } else {
                    if (!StringUt.isEmpty(vip)) {
                        if (vip.equals("1")) {
                            //是vip
                            SmartMediaPicker.builder(this)
                                    //最大图片选择数目 如果不需要图片 将数目设置为0
                                    .withMaxImageSelectable(0)
                                    //最大视频选择数目 如果不需要视频 将数目设置为0
                                    .withMaxVideoSelectable(1)
                                    //最大视频长度
                                    .withMaxVideoLength(600 * 1000)
                                    //最大视频文件大小 单位MB
                                    .withMaxVideoSize(1024)
                                    //设置图片加载引擎
                                    .withImageEngine(new Glide4Engine())
                                    //前置摄像头拍摄是否镜像翻转图像
                                    .withIsMirror(false)
                                    //弹出类别，默认弹出底部选择栏，也可以选择单独跳转
                                    .withMediaPickerType(MediaPickerEnum.BOTH)
                                    .build()
                                    .show();
                        } else {
                            //不是vip
                            SmartMediaPicker.builder(this)
                                    //最大图片选择数目 如果不需要图片 将数目设置为0
                                    .withMaxImageSelectable(0)
                                    //最大视频选择数目 如果不需要视频 将数目设置为0
                                    .withMaxVideoSelectable(1)
                                    //最大视频长度
                                    .withMaxVideoLength(60 * 1000)
                                    //最大视频文件大小 单位MB
                                    .withMaxVideoSize(1024)
                                    //设置图片加载引擎
                                    .withImageEngine(new Glide4Engine())
                                    //前置摄像头拍摄是否镜像翻转图像
                                    .withIsMirror(false)
                                    //弹出类别，默认弹出底部选择栏，也可以选择单独跳转
                                    .withMediaPickerType(MediaPickerEnum.BOTH)
                                    .build()
                                    .show();
                        }
                    } else {
                        SmartMediaPicker.builder(this)
                                //最大图片选择数目 如果不需要图片 将数目设置为0
                                .withMaxImageSelectable(0)
                                //最大视频选择数目 如果不需要视频 将数目设置为0
                                .withMaxVideoSelectable(1)
                                //最大视频长度
                                .withMaxVideoLength(60 * 1000)
                                //最大视频文件大小 单位MB
                                .withMaxVideoSize(1024)
                                //设置图片加载引擎
                                .withImageEngine(new Glide4Engine())
                                //前置摄像头拍摄是否镜像翻转图像
                                .withIsMirror(false)
                                //弹出类别，默认弹出底部选择栏，也可以选择单独跳转
                                .withMediaPickerType(MediaPickerEnum.BOTH)
                                .build()
                                .show();
                    }
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_address:
                startActivityForResult(new Intent(this, AddressListAc.class), 20);
                break;
            case R.id.bt_login:
                if (StringUt.isEmpty(et_title.getText().toString().trim())) {
                    Toast.makeText(this, "标题不可为空", Toast.LENGTH_SHORT).show();
                    return;
                } else if (StringUt.isEmpty(path)) {
                    Toast.makeText(this, "请上传视频", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    upload();
                }
                break;
        }
    }

    /**
     * 上传视频
     */
    private void upload() {
        title = et_title.getText().toString().trim();
        context = et_text.getText().toString().trim();
        showLoading();
        fileList.clear();
        fileList.add(new File(path));
        ApiUtil.getVideoApi().upload(filesToMultipartBody(fileList)).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<UploadBean>>() {
            @Override
            public void onSuccess(ApiResponse<UploadBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            video = data.getData().getInfo().get(0).getUrl();
                            addFilm();
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    /**
     * 发布视频
     */
    private void addFilm() {
        VideoChannelBody body = new VideoChannelBody();
        body.setTitle(title);
        body.setCover("");
        body.setChannelId("");
        body.setContext(context);
        body.setVideo(video);
        body.setIsPaid("1");
        body.setMoney("");
        body.setType(type);
        body.setCreateTime(TimeUtil.getCurrentDateTime("yyyy-MM-dd HH-mm-ss"));
        body.setUpdateTime(TimeUtil.getCurrentDateTime("yyyy-MM-dd HH-mm-ss"));
        ApiUtil.getVideoApi().addVideo(SPUtil.getToken(this), body).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<AddVideoBean>>() {
            @Override
            public void onSuccess(ApiResponse<AddVideoBean> data) {
                showSuccess();
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            dialogSuccess();
                        } else {
                            Toast.makeText(ShortVideoAc.this, data.getData().getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        }));
    }

    private void dialogSuccess() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(ShortVideoAc.this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(ShortVideoAc.this, R.layout.dialog_success, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        TextView tv_continue = view.findViewById(R.id.tv_continue);
        tv_continue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //继续
                dialog.dismiss();
                path = "";
                et_title.setText("");
                et_text.setText("");
                title = "";
                context = "";
                video = "";
                iv_up_video.setImageResource(R.mipmap.up_video_img);
                tv_address.setText("");
            }
        });

        TextView tv_black = view.findViewById(R.id.tv_black);
        tv_black.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回首页
                dialog.dismiss();
                finish();
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<String> resultData = SmartMediaPicker.getResultData(this, requestCode, resultCode, data);
        if (resultData != null && resultData.size() > 0) {
            path = String.valueOf(resultData.toArray()[0]);
            startActivity(new Intent(ShortVideoAc.this, ShortPreviewAc.class)
                    .putExtra("path", path));
            iv_delete.setVisibility(View.VISIBLE);
            iv_broadcast.setVisibility(View.VISIBLE);
            GlideImgManager.glideLoaderFile(ShortVideoAc.this, new File(path), iv_up_video, 1);
        } else {

        }

        if (resultCode == 20) {
            String name = data.getStringExtra("name");
            String address = data.getStringExtra("address");
            lat = data.getStringExtra("lat");
            lng = data.getStringExtra("lng");
            city = data.getStringExtra("city");
            tv_address.setText(name + address);
        }
    }

    public static MultipartBody filesToMultipartBody(List<File> files) {
        MultipartBody.Builder builder = new MultipartBody.Builder();

        for (File file : files) {
            // TODO: 16-4-2  这里为了简单起见，没有判断file的类型
            RequestBody requestBody = RequestBody.create(MediaType.parse("video/mp4"), file);
            builder.addFormDataPart("file", file.getName(), requestBody);
        }

        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }
}
